package cn.jbit.service.impl;

import cn.jbit.entity.Employee;
import cn.jbit.entity.EmployeeExample;
import cn.jbit.mapper.EmployeeMapper;
import cn.jbit.service.EmployeeService;
import cn.jbit.utils.jedisUtil;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ExceptionHandler;
import redis.clients.jedis.Jedis;
import sun.rmi.log.LogInputStream;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 财龙
 * @Description:
 * @date 2020/9/25 15:02
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    /* @Override
     public List<Employee> getEmployeeList() {
         return employeeMapper.selectByExampleWithDept(null);
     }*/
   @Override
   public String getEmployeeList() {
       //首次调用此方法就去Redis取
       Jedis jedis = jedisUtil.getJedis();
       String emps= jedis.get("emps");
       if(StringUtils.isEmpty(emps)){
           //为null,去 MySQL中查询,放入Redis中
           List<Employee> employeeList = employeeMapper.selectByExampleWithDept(null);
           String string = JSONArray.toJSONString(employeeList);
           //存入Redis
           jedis.set("emps", string);
           System.out.println("=======从MySQL中取==========");
           return string;
       }
       System.out.println("=======从Redis中取==========");
       return emps;
   }

    @Override
    public Boolean addEmployee(Employee employee) {
        int i = employeeMapper.insertSelective(employee);
        return i!=0;
    }

    @Override
    public Boolean checkEmpName(String name) {
        EmployeeExample employeeExample=new EmployeeExample();
        EmployeeExample.Criteria criteria = employeeExample.createCriteria();
        criteria.andEmpNameEqualTo(name);
        long count = employeeMapper.countByExample(employeeExample);
        return count==0;
    }
/*根据ID查询出员工信息*/
    @Override
    public Employee getEmployeeById(Integer empId) {
        return employeeMapper.selectByPrimaryKey(empId);
    }

    /**
     * 修改员工
     * @param employee
     */
    @Override
    public void updateEmployee(Employee employee) {
        employeeMapper.updateByPrimaryKeySelective(employee);
    }

    @Override
    public void delEmployeeById(Integer empId) {
        employeeMapper.deleteByPrimaryKey(empId);
    }

    /*根据ID集合删除多个*/
    @Override
    public void delEmployeeByIds(List<Integer> empId) {
        EmployeeExample employeeExample = new EmployeeExample();
        EmployeeExample.Criteria criteria = employeeExample.createCriteria();
        criteria.andEmpIdIn(empId);
        employeeMapper.deleteByExample(employeeExample);
    }

}
